﻿using System;
using System.Collections.Generic;
using System.Text;

namespace mqtttLib.Helper
{
    internal class MqttEncoding : UTF8Encoding
    {
        public override byte[] GetBytes(string s)
        {
            //ValidateString(s);
            var stringBytes = new List<byte>();
            int length = GetstringByteCount(s);
            stringBytes.Add((byte)(length >> 8));
            stringBytes.Add((byte)(length & 0xFF));
            stringBytes.AddRange(UTF8.GetBytes(s));
            return stringBytes.ToArray();
        }

        public int GetstringByteCount(string chars)
        {
            return UTF8.GetByteCount(chars);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public override string GetString(byte[] bytes)
        {
            return UTF8.GetString(bytes);
        }
        /// <summary>
        /// 得到 cahr的个数
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public override int GetCharCount(byte[] bytes)
        {
            if (bytes.Length < 2)
                throw new ArgumentException("字节数组必须有2字节");
            ushort result = (ushort)((bytes[0] << 8) + bytes[1]);

            return result;
        }

        public override int GetByteCount(string chars)
        {
            // ValidateString(chars);

            var  c=UTF8.GetByteCount(chars) + 2;
            if (c>50)
            {
                string ss = "";
            }
            return c;

        }

        //private static void ValidateString(string s)
        //{
        //    foreach (var c in s)
        //    {
        //        if (c > 0x7F)
        //            throw new ArgumentException("不支持，输入的字符串是扩展UTF");
        //    }
        //}
    }
}
